package com.quan.OGCamera;

import java.io.File;
import java.sql.Date;
import java.text.SimpleDateFormat;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

public class ImageManager {
	//This class handles images processing.
	
	public static final int MEDIA_TYPE_IMAGE = 1;
	//public static final int MEDIA_TYPE_VIDEO = 2;
	
	public static Bitmap workingImage = null;//Cache working progress
	
	
	
	
	
	// Merge 2 bitmap into 1, bmp2 on top of bmp 1 
		// Pre: bmp2 has the same size as bmp 1 
		// return bmOverlay with the same size as bmb 1
	public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
	    Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
	    Canvas canvas = new Canvas(bmOverlay);
	    canvas.drawBitmap(bmp1, new Matrix(), null);
	    canvas.drawBitmap(bmp2, 0, 0, null);
	    return bmOverlay;
	}
	
	// Merge 2 bitmap into 1, bmp2 on top of bmp 1, bmp2 will be draw at position (x,y) 
		// Coordinations start from the top left corner. 
		// return bmOverlay with the same size as bmb 1
	public static Bitmap overlayAtPosition(Bitmap bmp1, Bitmap bmp2, int x, int y) {
		Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
	    Canvas canvas = new Canvas(bmOverlay);
	    canvas.drawBitmap(bmp1, new Matrix(), null);
	    canvas.drawBitmap(bmp2, x, y, null);
	    return bmOverlay;
	}
	
	/** Create a file Uri for saving an image or video */
	public static Uri getOutputMediaFileUri(int type){
	      return Uri.fromFile(getOutputMediaFile(type));
	}
	
	/** Create a file Uri for saving an image or video temporary */
	public static Uri getTempMediaFileUri(int type, Context context){
	      return Uri.fromFile(getTempMediaFile(type,context));
	}

	/** Create a File for saving an image or video */
	private static File getOutputMediaFile(int type){
	    // check that the SDCard is mounted
	    // using Environment.getExternalStorageState() before doing this.

	    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
	              Environment.DIRECTORY_PICTURES), "OGCamera");
	    // This location works best for created images to be shared
	    // between applications and persist after your app has been uninstalled.

	    // Create the storage directory if it does not exist
	    if (! mediaStorageDir.exists()){
	        if (! mediaStorageDir.mkdirs()){
	            Log.d("OGCamera", "failed to create directory");
	            return null;
	        }
	    }

	    // Create a media file name
	    String timeStamp = SimpleDateFormat.getDateTimeInstance().format(new Date(type));
	    File mediaFile;
	    if (type == MEDIA_TYPE_IMAGE){
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
	        "IMG_"+ timeStamp + ".jpg");
	    } /*else if(type == MEDIA_TYPE_VIDEO) {
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
	        "VID_"+ timeStamp + ".mp4");
	    }*/ else {
	        return null;
	    }

	    return mediaFile;
	}
	
	private static File getTempMediaFile(int type, Context context){
	    // To be safe, you should check that the SDCard is mounted
	    // using Environment.getExternalStorageState() before doing this.

	    File tempStorageDir;// = new File(context.getCacheDir(), "OGCamera");
	    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
	        File externalRoot = Environment.getExternalStorageDirectory();
	        tempStorageDir = new File(externalRoot, ".myAppTemp");
	    } else {
	    	tempStorageDir = new File(context.getCacheDir(), "OGCamera");
	    }
	    // Create the storage directory if it does not exist
	    if (! tempStorageDir.exists()){
	        if (! tempStorageDir.mkdirs()){
	            Log.d("OGCamera", "failed to create directory");
	            return null;
	        }
	    }

	    // Create a media file name
	    File mediaFile;
	    if (type == MEDIA_TYPE_IMAGE){
	        mediaFile = new File(tempStorageDir.getPath() + File.separator +
	        "temp"+".ogc");
	    } /*else if(type == MEDIA_TYPE_VIDEO) {
	        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
	        "VID_"+ timeStamp + ".mp4");
	    }*/ else {
	        return null;
	    }

	    return mediaFile;
	}
	
	//Get drawable resource with name pDrawableName
	public static Drawable getAndroidDrawable(String pDrawableName, Context context){
	    int resourceId=context.getResources().getIdentifier(pDrawableName, "drawable", context.getPackageName());
	    if(resourceId==0){
	        return null;
	    } else {
	        return context.getResources().getDrawable(resourceId);
	    }
	}
	
	//Convert Drawable to Bitmap
	public static Bitmap drawableToBitmap (Drawable drawable) {
	    if (drawable instanceof BitmapDrawable) {
	        return ((BitmapDrawable)drawable).getBitmap();
	    }

	    int width = drawable.getIntrinsicWidth();
	    width = width > 0 ? width : 1;
	    int height = drawable.getIntrinsicHeight();
	    height = height > 0 ? height : 1;

	    Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
	    Canvas canvas = new Canvas(bitmap); 
	    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
	    drawable.draw(canvas);

	    return bitmap;
	}
	
	//Some phone keep another version of the image taken by the camera activity
	//This function return the last image keep in the publics gallery to find out if 
	//another version of the taken image is kept or not
	public static File lastFromDCIM() {
	    try {          
	    	File latestSavedImage = null;
	        //Samsungs:
	        File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM/Camera");
	        if (folder.exists()) {
	        	File[] images = folder.listFiles();
		        latestSavedImage = images[0];
		        for (int i = 1; i < images.length; ++i) {
		            if (images[i].lastModified() > latestSavedImage.lastModified()) {
		                latestSavedImage = images[i];
		            }
		        }
	        }
	        //other phones/app:
            File[] subfolders = new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM").listFiles();
            for(File subfolder : subfolders){
                if(subfolder.getAbsolutePath().contains("100")){  
                    folder = subfolder;
                    break;
                }
            }
            if(!folder.exists())
                return null;
            
	        File[] images = folder.listFiles();
	        latestSavedImage = images[0];
	        for (int i = 1; i < images.length; ++i) {
	            if (images[i].lastModified() > latestSavedImage.lastModified()) {
	                latestSavedImage = images[i];
	            }
	        }            
	        return latestSavedImage;
	    } catch (Exception e) {
	        e.printStackTrace();
	        return null;
	    }

	}
}
